package Zoo.Handler;

import Zoo.View.RegisterView.RegisterView;
import com.dao.Insert;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.SQLException;

public class RegisterHandler extends KeyAdapter implements ActionListener {
    private RegisterView registerView;

    public RegisterHandler(RegisterView registerView){
        this.registerView=registerView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton=(JButton) e.getSource();
        String text =jButton.getText();
        if("重置".equals(text)){
            registerView.getUserTxt().setText("");
            registerView.getPwdField().setText("");
            registerView.getPhoneTxt().setText("");
        }else if("注册".equals(text)){
            try {
                register();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void register() throws SQLException {
        String user = registerView.getUserTxt().getText();
        char[] chars = registerView.getPwdField().getPassword();
        String phone = registerView.getPhoneTxt().getText();
        //校验密码和用户名是否为空
        if(user==null||"".equals(user.trim())||chars==null||phone==null||"".equals(phone.trim())){
            JOptionPane.showMessageDialog(registerView,"用户名，密码和联系电话必填");
            return;
        }
        String pwd =new String(chars);
        System.out.println(user+":"+pwd);
        System.out.println(phone);

//        //查询db
//        AdminService adminService = new AdminServiceImpl();
//        AdminEntity adminEntity=new AdminEntity();
//        adminEntity.setUsername(user);
//        adminEntity.setPwd(pwd);
//        boolean flag=adminService.validateAdmin(adminEntity);
//        if(flag){
//            //跳转到主界面并销毁登录界面
//
//            new JtableDemo();
//            registerView.dispose();
//
//        }else{
//            JOptionPane.showMessageDialog(registerView,"用户名和密码错误");
//        }
        //插入数据（注册用户）
        Insert in=new Insert();
        in.insert(user,pwd,phone);
        JOptionPane.showMessageDialog(registerView,"已注册成功，请重新打开窗口并登录");
    }

    //注册的时候可以按注册按钮，也可以按回车
    @Override
    public void keyPressed(KeyEvent e) {
        e.getKeyCode();
        if(KeyEvent.VK_ENTER==e.getKeyCode()) {
            try {
                register();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}
